package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 查询用户余额
     * @param
     */
    @Override
    @Transactional
    public void updateUserBalance(Long id,Integer money) {
        // 判断用户的状态是否正常
        User user = getById(id);
        if (user == null || user.getStatus() == 2){
            throw new RuntimeException("用户状态不正常，无法操作");
        }

        // 判断用户余额是否充足
        if (user.getBalance() < money){
            throw new RuntimeException("用户余额不足，无法操作");
        }

        // 修改用户余额
        int remainBalance =  user.getBalance()-money;
        lambdaUpdate()
                .set(User::getBalance,remainBalance) // 更新余额
                .set(remainBalance == 0,User::getStatus,2) // 动态判断是否更新status
                .eq(User::getId,id)
                .eq(User::getBalance,remainBalance) //乐观锁
                .update();
        updateById(user);
    }

    /**
     * 分页查询用户列表
     * @param userQuery 查询条件
     * @return
     */
    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        // 1.构造查询条件
        // 1.1.构建分页条件
        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
        // 1.2.排序条件
        if (userQuery.getSortBy() != null){
            page.addOrder(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
        }else {
            // 默认按照更新时间排序
            page.addOrder(new OrderItem("update_time", false));
        }


/*        // 2.查询
        Page<User> p = lambdaQuery()
                .like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .page(page);

        // 3.数据非空检验
        List<User> records = p.getRecords();
        if (records == null || records.isEmpty()){
            // 无数据返回空结果
            return new PageDTO<>(p.getTotal(), p.getPages(), Collections.emptyList());
        }

        // 4.有数据转换
        List<UserVO> list = BeanUtil.copyToList(records, UserVO.class);

        // 5.封装换回
        return new PageDTO<UserVO>(p.getTotal(),p.getPages(),list);*/

        // 通过mapper层调用可用于复杂多表的分页查询
        IPage<UserVO> iPage = userMapper.selectUserPage(page, userQuery);
        return new PageDTO<>(iPage.getTotal(), iPage.getPages(), iPage.getRecords());
    }
}
